package servlets.adsServlets;

import java.io.IOException;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.JsonManager;

import org.jsoup.Jsoup;

import structures.ADsList;

public class ShowTiVendoIoAds extends HttpServlet {

	private static final String URLBASE = "http://localhost:8080/ISellToYouRESTWebService/GetTiVendoIoADs";
	private static final long serialVersionUID = 2563250178012340372L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String answer, starterId, limit, adType, method;
		
		URL url;
		JsonManager jsonManager;
		ADsList adsList = null;
		jsonManager = new JsonManager();
		starterId = request.getParameter("starterId");
		method = request.getParameter("method");
		limit = request.getParameter("limit");
		adType = request.getParameter("adType");
		
		try {
			url = new URL(URLBASE + "?limit=" + limit + "&starterId=" + starterId + "&method=" + method + "&adType=" + adType);
			answer = Jsoup.connect(url.toString()).ignoreContentType(true).execute().body();
			
			System.out.println(answer);
        	System.out.flush();
			
			if(answer.equals("null"))
				throw new Exception();
			
			
			adsList = jsonManager.toADsList(answer);
        	
			request.getSession().setAttribute("adsList", adsList);
			try {
				response.sendRedirect(request.getContextPath() + "/advertisements.jsp");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			try {
				response.sendRedirect(request.getContextPath() + "/advertisements.jsp");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
